﻿using System;
using System.Drawing;
using System.Windows.Forms;

using OpenTK;
using OpenTK.Input;

namespace MosCraft.Utilities.Input
{
    public static class MouseHelper
    {
        private static GameWindow ActiveGameWindow;
        private static MouseDevice mouse;
        private static bool Grabbed;
        private static float Sensitivity;

        public static float Yaw;
        public static float Pitch;

        /// <summary>
        /// Initialize the mouse handler
        /// </summary>
        /// <param name="form">GameWindow handle</param>
        static internal void Initialize(GameWindow gamewindow)
        {
            ActiveGameWindow = gamewindow;
            mouse = gamewindow.Mouse;
        }

        /// <summary>
        /// Grabs the mouse to the GameWindow
        /// </summary>
        static internal void GrabMouse()
        {
            Grabbed = true;
        }

        /// <summary>
        /// Sets how fast the mouse should be moved per delta
        /// </summary>
        /// <param name="sensitivity"></param>
        static internal void SetSensitivity(float sensitivity)
        {
            Sensitivity = sensitivity;
        }

        /// <summary>
        /// Updates the mouse state
        /// </summary>
        static internal void Update()
        {
            bool windowFocused = ActiveGameWindow.Focused;

            if (Grabbed && windowFocused)
            {
                Point center = new Point(ActiveGameWindow.Width / 2, ActiveGameWindow.Height / 2);
                Yaw -= (mouse.X - center.X) * Sensitivity;
                Pitch -= (mouse.Y - center.Y) * Sensitivity;

                if (Pitch > 1.55f)
                    Pitch = 1.55f;

                if (Pitch < -1.55f)
                    Pitch = -1.55f;

                Cursor.Position = ActiveGameWindow.PointToScreen(center);
                Cursor.Hide();
            }
            else
            {
                Cursor.Show();
            }
        }
    }
}
